package com.hula.onion.book.server.spider.platforms.renrendai;

import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import com.hula.onion.book.server.utils.CookieUtils;
import com.hula.onion.book.server.utils.DateUtils;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Description:
 * Create Date:2018/1/17 19:33
 *
 * @author shan
 * @version 1.0
 */
@Component("renrenDaiSpider")
public class RenrenDaiSpider extends SpiderCommon {
    /**
     * 登录URL
     */
    private static final String LOGIN_URL = "https://www.renrendai.com/pc/passport/index/doLogin";

    /**
     * 验证码URL
     */
    private static final String CAPTCHA_URL = "https://www.renrendai.com/pc/passport/index/captcha?time=";

    /**
     * 获取账户信息URL
     */
    private static final String GET_ACCOUNT_INFO_URL = "https://www.renrendai.com/account/getHomePageUserInfo.action?timeout=5000&_=";

    @Autowired
    private RenrenDaiSpiderHelper renrenDaiSpiderHelper;

    /**
     * 执行爬取操作
     * 1.获取 RSA key
     * 2.组装模拟登陆参数，模拟登陆
     * 3.爬取用户详细信息
     */
    @Override
    public CommonResponse execute() {

        CommonResponse commonResponse = new CommonResponse(ResponseStatusEnum.FAIL);

        try {
            //1.1 组装模拟登陆参数
            Map<String, Object> paramMap = renrenDaiSpiderHelper.installRequestParams(loginForm);

            HttpClientContext httpContext = HttpClientContext.create();
            BasicCookieStore cookieStore = new BasicCookieStore();
            httpContext.setCookieStore(cookieStore);

            //获取loginform中的cookie
            CookieUtils.writeCookieFromRequest(cookieStore, loginForm.getRequest(), "www.renrendai.com", "/");

            //1.2 模拟登陆
            String responseStr = HttpUtils.post(LOGIN_URL, paramMap, httpContext);

            logger.info("[RenrenDaiSpider] Http response result:{}", responseStr);

            int status = JSONObject.parseObject(responseStr).getInteger("status");
            //登陆成功
            if (status == 0) {
                //抓取数据
                String html = HttpUtils.get(GET_ACCOUNT_INFO_URL + DateUtils.getCurrentMillisecond(),
                        httpContext);

                AccountInfo balance = renrenDaiSpiderHelper.parseAccountBalance(html);

                commonResponse = new CommonResponse(ResponseStatusEnum.SUCCESS);
                commonResponse.setData(balance);

                return commonResponse;

            } else {
                boolean isShowCaptcha =
                        JSONObject.parseObject(responseStr).getJSONObject("data").getBoolean("isShowCaptcha");

                //显示图片验证码
                if (isShowCaptcha) {
                    commonResponse = new CommonResponse(ResponseStatusEnum.NEED_CAPTURE);

                    commonResponse.setCode(JSONObject.parseObject(responseStr).getString("status"));
                    commonResponse.setMsg(JSONObject.parseObject(responseStr).getString("message"));

                    //写入cookie
                    CookieUtils.writeCookieFromHttpClientContext(httpContext, loginForm.getResponse());

                    return commonResponse;
                }

                commonResponse.setMsg(JSONObject.parseObject(responseStr).getString("message"));
                commonResponse.setCode(JSONObject.parseObject(responseStr).getString("status"));
            }

        } catch (Exception e) {
            logger.error("[NiWoDaiSpider] Install request params error!");
        }

        return commonResponse;
    }

    @Override
    public String getCaptchaURL() {
        return CAPTCHA_URL + System.currentTimeMillis();
    }
}
